const co = require('co')
const fs = require('fs')
const URL = require('url')
const http = require('http')
const zlib = require('zlib')
const querystring = require('querystring')

const conf = require('./conf')

const proxy = {}

proxy.GET = function(path, headers) {
    return request(false, path, headers)
}

proxy.POST = function(path, headers, form) {
    return request(true, path, headers, form)
}

function request(isPOST, path, headers, form) {
    return function(cb) {
        headers = headers || {}
        form = form || {}
        let postData = querystring.stringify(form)
        let options = URL.parse('http://' + conf.server + path.split(conf.server)[1])
        options.method = isPOST ? 'POST' : 'GET'
        options.headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,ja;q=0.7,zh-TW;q=0.6',
            'Cache-Control': 'max-age=0',
            'Connection': 'keep-alive',
            'Host': options.host,
            'Origin': 'http://' + options.host,
            'Referer': 'http://' + options.host + path,
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        }
        if (isPOST) {
            options.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
            options.headers['Content-Length'] = postData.length
            options.headers['Referer'] = `http://ks.wjx.top/m/${conf.pid}.aspx`
        }
        for (let k in headers) {
            options.headers[k] = headers[k]
        }
        let req = http.request(options, (res) => {
            res.setTimeout(3000)
            let data = []
            res.on('data', (chunk) => {
                data.push(chunk)
            })
            res.on('end', () => {
                let body = data.join('')
                if (res.headers['content-encoding'] == 'gzip') { // Gzip支持
                    zlib.gunzip(Buffer.concat(data), function(err, decoded) {
                        if (err) {
                            conf.dev && fs.writeFileSync(options.host + '.html', body)
                            cb(null, { code: res.statusCode, headers: res.headers, body: body })
                        } else {
                            conf.dev && fs.writeFileSync(options.host + '.html', decoded.toString())
                            cb(null, { code: res.statusCode, headers: res.headers, body: decoded.toString() })
                        }
                    })
                } else {
                    conf.dev && fs.writeFileSync(options.host + '.html', body)
                    cb(null, { code: res.statusCode, headers: res.headers, body: body })
                }
            })
        })
        req.setTimeout(3000)
        req.on('error', (err) => {
            cb(err, err.message)
        })
        if (isPOST) {
            req.write(postData)
        }
        req.end()
    }
}

module.exports = proxy